import { Input, OnInit, Directive, NgZone, ChangeDetectorRef } from '@angular/core';
import {
  CdkOverlayOrigin,
  ConnectionPositionPair,
} from '@angular/cdk/overlay';
import { BehaviorSubject } from 'rxjs';

import { POSITION_MAP, Placement } from './position-map';

@Directive()
export abstract class OverlayEntry {
  /**
   * entry是否显示
   */
  visible = new BehaviorSubject<boolean>(false);

  // placement = new BehaviorSubject<Placement>(null);

  overlayOrigin: CdkOverlayOrigin;

  positions: ConnectionPositionPair[] = [];

  direction: string;

  constructor(
  ) { }

  show() {
    this.visible.next(true);
  }

  hide() {
    this.visible.next(false);
  }

  /**
   *
   *
   * 设置entry的方向
   *
   *
   *
   * @param direction
   */
  setPosition(direction: string) {}

  /**
   * cdk positionChange回调默认方法。
   * 寻找预定义的direction继承类设置方向方法
   *
   * @param  {} $event
   */
  onPositionChange($event) {
    const pair: ConnectionPositionPair = $event.connectionPair;
    const direction = Object.keys(POSITION_MAP).find((mapKey) => {
      const mapPair = POSITION_MAP[mapKey];
      return this.isPositionEqual(pair, mapPair);
    });

    if (direction) {
      this.setPosition(direction);
    }
  }

  setOverlayOrigin(origin: CdkOverlayOrigin) {
    this.overlayOrigin = origin;
  }
  /**
   * 判断两个position是否值相等
   *
   * @param p1
   * @param p2
   */
  isPositionEqual(p1: ConnectionPositionPair, p2: ConnectionPositionPair) {
    const notEqualProperty = Object.getOwnPropertyNames(p1).find((property) => p1[property] !== p2[property]);

    return !notEqualProperty;
  }

  toSnake(camel: string) {
    return camel.split(/(?=[A-Z])/).join('-').toLowerCase();
  }

  /**
   * 获取方向，topRight -> top
   *
   * @param camel
   */
  toDirection(camel: Placement) {
    return camel.split(/(?=[A-Z])/)[0];
  }
}
